package com.ctg.itrdc.imageconsole.data.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.constants.DockerConstant;
import com.ctg.itrdc.imageconsole.data.dao.IDockerImageTagDao;
import com.ctg.itrdc.imageconsole.data.dto.DockerImageIndexDTO;
import com.ctg.itrdc.imageconsole.data.entity.DockerImageTag;
import com.ctg.itrdc.imageconsole.data.entity.user.DockerMicroUser;
import com.ctg.itrdc.paspsdk.common.entity.PageInfo;
import com.ctg.itrdc.paspsdk.common.utils.type.StringUtils;
import com.ctg.itrdc.paspsdk.data.dao.impl.BaseDaoImpl;
import com.ctg.itrdc.paspsdk.data.entity.ClassInfoUtils;

@Component("dockerImageTagDao")
public class DockerImageTagDaoImpl extends BaseDaoImpl implements IDockerImageTagDao {
	@SuppressWarnings("unchecked")
	public PageInfo<DockerImageTag> jdbcFindPageInfo(DockerImageTag entity, int currentPage, int perPageNum) {
		// String
		// sql="select
		// PRODUCT_ID,PRODUCT_NAME,CREATE_STAFF,PROD_FUNC_TYPE,UPDATE_DATE,REMARK,EFF_DATE,STATUS_DATE,MANAGE_GRADE,PRODUCT_NBR,UPDATE_STAFF,EXP_DATE,PRODUCT_DESC,PRODUCT_TYPE,STATUS_CD,CREATE_DATE,DEFAULT_NUMBER
		// from pz_cp_prod where PRODUCT_ID = 14 ";
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();
		if (entity.getId() != null) {
			sql.append(" and id = ?");
			params.add(entity.getId());
		}

		return (PageInfo<DockerImageTag>) this.jdbcFindPageInfo(sql.toString(), entity.getClass(), params,
				currentPage, perPageNum, true);
	}

	@Override
	public DockerImageTag findDockerImageIndex(Long pserverId, Long imageFileId, String version) {
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();
		sql.append(" AND DOCKER_PSERVER_ID = ? ");
		params.add(pserverId);
		sql.append(" AND DOCKER_IMAGE_FILE_ID = ? ");
		params.add(imageFileId);
		sql.append(" AND VERSION = ? ");
		params.add(version);
		List<DockerImageTag> list = this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	private StringBuffer basicSql() {
		String columnsName = ClassInfoUtils.getColumnsName(DockerImageTag.class);
		String tableName = ClassInfoUtils.getTableName(DockerImageTag.class);
		StringBuffer sql = new StringBuffer(" SELECT ");
		sql.append(columnsName).append(" FROM ").append(tableName).append(" WHERE 1=1");
		return sql;
	}

	@Override
	public List<DockerImageTag> findEveryImagesGroupBy(List<Long> pserverIds) {
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();

		sql.append(" and STATE =?");
		params.add(DockerConstant.DockerImageCons.UNSTABLE);
		sql.append(" and DOCKER_PSERVER_ID in(");
		for (int i = 0, len = pserverIds.size(); i < len; i++) {
			if (i == 0) {
				sql.append("?");
			} else {
				sql.append(",?");
			}
			params.add(pserverIds.get(i));
		}
		sql.append(") group by DOCKER_IMAGE_FILE_ID,VERSION");
		List<DockerImageTag> list = this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}

	@Override
	public List<DockerImageTag> findIndexsByfileIdAndVersion(List<Long> pserverIds, Long imageFileId,
			String version) {
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();

		sql.append(" and STATE =?");
		params.add(DockerConstant.DockerImageCons.UNSTABLE);
		sql.append(" and DOCKER_IMAGE_FILE_ID =?");
		params.add(imageFileId);
		sql.append(" and VERSION =?");
		params.add(version);
		sql.append(" and DOCKER_PSERVER_ID in(");
		for (int i = 0, len = pserverIds.size(); i < len; i++) {
			if (i == 0) {
				sql.append("?");
			} else {
				sql.append(",?");
			}
			params.add(pserverIds.get(i));
		}
		sql.append(") ");
		List<DockerImageTag> list = this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}

	@Override
	public List<DockerImageTag> findNormalDockerImageIndex(List<Long> pserverIds) {

		if (pserverIds.size() == 0) {
			return new ArrayList<DockerImageTag>();
		}

		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();
		sql.append(" and STATE in('000','001')");
		if (pserverIds.size() > 0) {
			sql.append(" and DOCKER_PSERVER_ID in(");
			for (int i = 0, len = pserverIds.size(); i < len; i++) {
				if (i == 0) {
					sql.append(pserverIds.get(i).toString());
				} else {
					sql.append(",").append(pserverIds.get(i).toString());
				}
				// params.add(pserverIds.get(i));
			}
			sql.append(") ");
		}

		return this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
	}

	/**
	 * 更新正常
	 */
	public void updateNormalDockerImageIndexState(List<Long> dockerImageIndexList) {
		String tableName = ClassInfoUtils.getTableName(DockerImageTag.class);
		StringBuilder sql = new StringBuilder("update ").append(tableName).append(" set STATE='001' ")
				.append(" where ID in(");

		for (int i = 0, len = dockerImageIndexList.size(); i < len; i++) {
			if (i == 0) {
				sql.append(dockerImageIndexList.get(i).toString());
			} else {
				sql.append(",").append(dockerImageIndexList.get(i).toString());
			}
		}
		sql.append(") ");
		this.getJdbcTemplate().update(sql.toString(), new Object[] {});

	}

	@Override
	public DockerImageTag findByServerIdImageNameVersion(Long pserverId, String imageName, String version) {
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();
		if (pserverId != null) {
			sql.append(" AND DOCKER_PSERVER_ID = ? ");
			params.add(pserverId);
		}
		if (StringUtils.isNotEmpty(imageName)) {
			sql.append(" AND IMAGE_NAME = ? ");
			params.add(imageName);
		}
		if (StringUtils.isNotEmpty(version)) {
			sql.append(" AND VERSION = ? ");
			params.add(version);
		}
		sql.append(" ORDER BY LAST_UPDATE_TIME DESC");
		List<DockerImageTag> list = this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public PageInfo<DockerImageIndexDTO> findByImageFileId(Long imageFileId, Integer currentPage, Integer perPageNum) {

		String columnsName = ClassInfoUtils.getColumnsName(DockerImageTag.class);
		String tableName = ClassInfoUtils.getTableName(DockerImageTag.class);
		StringBuffer sql = new StringBuffer(" SELECT ");
		sql.append(columnsName).append(", SUM(DOWN_NUM) AS TOTAL_DOWN_NUM ");
		sql.append(" FROM ").append(tableName).append(" WHERE 1=1");
		List<Object> params = new ArrayList<Object>();
		sql.append(" AND STATE != ? ");
		params.add(DockerConstant.DockerImageIndexCons.REMOVE);
		sql.append(" AND DOCKER_IMAGE_FILE_ID = ? ");
		params.add(imageFileId);
		sql.append(" GROUP BY VERSION ORDER BY LAST_UPDATE_TIME DESC");
		return this.jdbcFindPageInfo(sql.toString(), DockerImageIndexDTO.class, params, currentPage, perPageNum);
	}

	@Override
	public List<DockerImageTag> findByDockerPserverId(Long dockerPserverId) {
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();
		sql.append(" AND DOCKER_PSERVER_ID = ? ");
		params.add(dockerPserverId);
		return this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ctg.itrdc.imageconsole.data.dao.IDockerImageIndexDao#
	 * findByImageFileIdAndVersion(java.lang.Long, java.lang.String)
	 */
	@Override
	public List<DockerImageTag> findByImageFileIdAndVersion(Long imageFileId, String version) {
		StringBuffer sql = basicSql();
		List<Object> params = new ArrayList<Object>();

		sql.append(" and DOCKER_IMAGE_FILE_ID =?");
		params.add(imageFileId);
		sql.append(" and VERSION =?");
		params.add(version);
		List<DockerImageTag> list = this.jdbcFindList(sql.toString(), DockerImageTag.class, params);
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}

	@Override
	public DockerImageTag selectByImageNameAndVersion(String imageName, String version) {
		// added by Shizhu.Peng on Nov.9
		String sql = "select * from docker_image_tag where image_name = ? and tag = ?";
		List<Object> params = new ArrayList<Object>();
		params.add(imageName);
		params.add(version);
		List<DockerImageTag> list = super.jdbcFindList(sql, DockerImageTag.class, params);
		if (list.size() > 1)
			throw new RuntimeException(list.size() + " docker_image_tag records found");
		return list.isEmpty() ? null : list.get(0);
	}

	@Override
	public DockerImageTag selectById(Long id) {
		DockerImageTag dockerImageIndex = new DockerImageTag();
		dockerImageIndex.setId(id);
		return super.selectByPrimaryKey(dockerImageIndex);
	}

	@Override
	public DockerImageTag queryNormalStateByEntity(String imageName, String version) {
		String sql = "select * from docker_image_index where image_name = ? and version = ? and state != ?";
		List<Object> params = new ArrayList<Object>();
		params.add(imageName);
		params.add(version);
		params.add(DockerConstant.DockerImageIndexCons.REMOVE);
		List<DockerImageTag> list = super.jdbcFindList(sql, DockerImageTag.class, params);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<DockerImageTag> selectByImageName(String imageName) {
		DockerImageTag imageTag = new DockerImageTag();
		imageTag.setImageName(imageName);
		return super.selectByExample(imageTag);
	}

	@Override
	public List<DockerImageTag> selectByTagIdMap(String imageName, Map<Long, Long> tagIdMap) {
		List<DockerImageTag> imageTags = new ArrayList<>();
		
		DockerImageTag tmpObj = null;
		DockerMicroUser microUser = null;
		for(Map.Entry<Long, Long> entry : tagIdMap.entrySet()){
			tmpObj = new DockerImageTag();
			tmpObj.setId(entry.getKey());
			DockerImageTag imageTag = super.selectByPrimaryKey(tmpObj);
			if(imageName.equals(imageTag.getImageName())){
				microUser = new DockerMicroUser();
				microUser.setSysUserId(entry.getValue());
				microUser.setAvailable(1);
				microUser = super.selectByExample(microUser).get(0);
				imageTag.setUserCodeOfShare(microUser.getCode());
				imageTags.add(imageTag);
			}
		}
		
		return imageTags;
	}
}
